package com.siruier.boss.ui.fragment.order

import android.os.Bundle
import android.view.View
import androidx.core.view.children
import androidx.core.view.forEach
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.siruier.boss.R
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.GiftOrderDetailBean
import com.siruier.boss.bean.GiftWarehouseSendStateEnum
import com.siruier.boss.common.formatPrice
import com.siruier.boss.databinding.FragmentGiftWarehouseListBinding
import com.siruier.boss.databinding.ItemGiftWarehouseBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.helper.ShareHelper.orderTransfer
import com.siruier.boss.ui.helper.pay
import com.siruier.boss.ui.helper.payChannel
import com.siruier.boss.ui.listener.OnTabSelectedListener
import kotlinx.coroutines.suspendCancellableCoroutine
import java.math.BigDecimal
import kotlin.coroutines.resume

class GiftWarehouseSendFragment : GiftWarehouseListFragment<FragmentGiftWarehouseListBinding>() {
    companion object {
        private val stateEnumMap = GiftWarehouseSendStateEnum.values().associateBy { it.state }
        private val stateEnum = GiftWarehouseSendStateEnum.values()
    }

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        stateEnum.forEach { state ->
            vb.tabLayout.addTab(vb.tabLayout.newTab().setText(state.stateName))
        }
        vb.tabLayout.addOnTabSelectedListener(OnTabSelectedListener { mRefreshHelper.onRefresh() })

        super.initView(rootView, savedInstanceState)
        mGiftWarehouseAdapter.setOnClickAdapterListenter(::onClick)
    }

    override fun onReload() {
        launchUI({
            mallApi.giveOrder(
                stateEnum[vb.tabLayout.selectedTabPosition].state,
                mRefreshHelper.page
            ).toData()?.records
        }, mRefreshHelper.handApiObserver())
    }

    private fun onClick(view: View, position: Int) {
        val bean = mGiftWarehouseAdapter.getItem(position)
        launchUI({
            when (view.id) {
                R.id.button_cancel_order -> {
                    val cancelOrder = suspendCancellableCoroutine<Boolean> { coroutine ->
                        showAlertDialog {
                            message(message = "确定取消订单吗?")
                            negativeButton { coroutine.resume(false) }
                            positiveButton { coroutine.resume(true) }
                        }
                    }
                    if (cancelOrder) {
                        mallApi.cancelOrder(bean.orderSn).toData()
                    }
                    cancelOrder
                }
                R.id.button_pay_order -> {
                    val activity = (context as BaseActivity<*>)
                    var discount = BigDecimal.ZERO
                    if (bean.goodsType in 2..3) {
                        discount = mallApi.discount(null, bean.orderSn, null).toData()?.discount
                            ?: BigDecimal.ZERO
                    }
                    val payChannel = activity.payChannel(bean.orderPrice, discount)
                    payChannel.orderSn = bean.orderSn
                    activity.pay(payChannel)
                }
                R.id.button_increase -> {
                    val goods = bean.goodsList[0]
                    orderTransfer(
                        mThis,
                        vb.viewOrderTransfer,
                        goods.picUrl,
                        goods.goodsName,
                        goods.vipPriceDesc,
                        goods.marketPriceDesc,
                        bean.orderSn
                    )
                    true
                }
                R.id.button_cancel_increase -> {
                    val cancelTransfer = suspendCancellableCoroutine<Boolean> { coroutine ->
                        showAlertDialog {
                            message(message = "确定取消赠送吗?")
                            negativeButton { coroutine.resume(false) }
                            positiveButton { coroutine.resume(true) }
                        }
                    }
                    if (cancelTransfer) {
                        mallApi.cancelTransfer(bean.orderSn).toData()
                    }
                    cancelTransfer
                }
                else -> false
            }
        }, ApiObserver(context, showLoadingDialog = false) {
            if (true == it) {
                mRefreshHelper.onRefresh()
            }
        })
    }

    override fun onBindViewHolder(
        vb: ItemGiftWarehouseBinding,
        bean: GiftOrderDetailBean,
        position: Int
    ) {
        vb.tvState.text = stateEnumMap[bean.status]?.stateName ?: ""
        vb.llButton.forEach { it.isVisible = false }
        when (bean.status) {
            GiftWarehouseSendStateEnum.WAIT_PAY.state -> {
                vb.buttonCancelOrder.isVisible = true
                vb.buttonPayOrder.isVisible = true
            }
            GiftWarehouseSendStateEnum.WAIT_TRANSFER.state -> {
                vb.buttonCancelOrder.isVisible = bean.goodsType !in 2..3
                vb.buttonIncrease.isVisible = true
            }
            GiftWarehouseSendStateEnum.HAVE_TRANSFER.state -> {
                vb.buttonIncrease.isVisible = true
                vb.buttonCancelIncrease.isVisible = true
            }
        }
        vb.llButton.isGone = vb.llButton.children.all { it.isGone }
        vb.tvGiveTime.isVisible = bean.giveTime.isNotEmpty()
        vb.tvGiveTime.text = "${bean.giveTime}送出"
        vb.tvReceiveUserPhone.isVisible = bean.receiveUserPhone.isNotEmpty()
        vb.tvReceiveUserPhone.text = "已被${bean.receiveUserPhone}于${bean.receiveTime}接收"
        mGiftWarehouseAdapter.setViewClick(
            position, vb.buttonCancelOrder, vb.buttonPayOrder,
            vb.buttonIncrease, vb.buttonCancelIncrease
        )
    }
}